<template>

    角色名称: <el-input v-model="page.roleName" style="width: 200px;" />
    <el-button type="primary" @click="getRoleList">查询</el-button>

    <el-table :data="roleList" border style="width: 100%;text-align: center;margin-top: 10px;">
        <el-table-column type="index" :index="indexMethod" label="编号" />
        <el-table-column prop="roleName" label="角色名称">
            <template v-slot="scope">
                <span @click="openDelUserRole(scope.row)">{{ scope.row.roleName }}</span>
            </template>
        </el-table-column>
        <el-table-column prop="createName" label="创建人" />
        <el-table-column prop="createTime" label="创建日期">
            <template v-slot="scope">
                <el-text v-if="scope.row.createTime == null ? '' : scope.row.createTime">{{
        scope.row.createTime.replace("T", " ").substring(0, 19) }}</el-text>
            </template>
        </el-table-column>
        <el-table-column prop="updateName" label="修改人" />
        <el-table-column prop="updateTime" label="修改日期">
            <template v-slot="scope">
                <el-text v-if="scope.row.updateTime == null ? '' : scope.row.updateTime">{{
        scope.row.updateTime.replace("T", " ").substring(0, 19) }}</el-text>
            </template>
        </el-table-column>
        <el-table-column prop="address" label="操作" width="230">
            <template v-slot="scope">
                <el-button type="primary" size="small"
                    @click="router.push({ name: 'RoleUpdate', query: { roleId: scope.row.roleId } })">修改</el-button>
                <el-button type="danger" size="small" @click="delRole(scope.row)">删除</el-button>
                <el-button type="warning" size="small" @click="openUserRoleAdd(scope.row)">分配人员</el-button>
            </template>
        </el-table-column>
    </el-table>


    <!-- 用户角色添加/返填对话框 -->
    <el-dialog v-model="dialogFormVisible" style="width: 600px;height: 500px;" :before-close="handleClose">

        <div class="common-layout">
            <el-container>
                <el-header>
                    <h2 style="font-weight: bolder;">请设置 <span style="color: red;font-weight: bolder;">【{{ roles
                            }}】</span>角色的员工
                    </h2>
                </el-header>
                <el-container>
                    <el-aside width="200px">
                        <el-tree :default-expand-all="true" :data="data" :props="defaultProps" show-checkbox
                            style="width: 200px" @check-change="getUserList" node-key="value"
                            :default-checked-keys="defaultCheckedDepartmentId" />
                    </el-aside>
                    <el-container>
                        <el-main>
                            <el-tree :default-expand-all="true" :data="defaultProps0" show-checkbox
                                :props="defaultProps1" style="width: 200px" @check-change="getUserId" node-key="id"
                                :default-checked-keys="defaultCheckedUserId" />
                        </el-main>
                    </el-container>
                </el-container>
            </el-container>
        </div>
        <template #footer>
            <div class="dialog-footer">
                <el-button type="primary" @click="addUserRole()">确认保存</el-button>
            </div>
        </template>
    </el-dialog>

    <!-- 角色删除对话框 -->
    <el-dialog v-model="dialogTableVisible" width="800" :show-close="false" :before-close="handleClose">
        <el-button link style="float: right;font-weight: bolder;" @click="dialogTableVisible = false">*关闭*</el-button>
        <span>属于角色 <span style="color: red;font-weight: bolder;">【{{ roles }}】</span>的员工如下:</span>
        <el-table :data="roleUser">
            <el-table-column property="userName" />
            <el-table-column>
                <template v-slot="scope">
                    <el-button link style="font-size: larger;" @click="delUserRole(scope.row)">×</el-button>
                    <el-button link @click="openUserRoleAdd1(scope.row)">✚</el-button>
                </template>
            </el-table-column>
        </el-table>
    </el-dialog>



    <table>
        <tr>
            <td>
                <el-pagination v-model:current-page="page.pageIndex" v-model:page-size="page.pageSize"
                    :page-sizes="[3, 5, 8]" :background="true" layout="total, slot, prev, pager, next" prev-text="上一页"
                    next-text="下一页" :total="page.totalCount" @size-change="handleSizeChange"
                    @current-change="handleCurrentChange">
                    <span>,每页{{ page.pageSize }}条,当前第{{ page.pageIndex }}/{{ page.totalPage }}页</span>
                    <el-button @click="handleCurrentChange(1)" :disabled="page.pageIndex == 1"
                        class="btn-prev">首页</el-button>
                </el-pagination>
            </td>
            <td>
                <el-pagination v-model:current-page="page.pageIndex" v-model:page-size="page.pageSize"
                    :page-sizes="[3, 5, 8]" :background="true" layout="slot, sizes, jumper" prev-text="上一页"
                    next-text="下一页" :total="page.totalCount" @size-change="handleSizeChange"
                    @current-change="handleCurrentChange">
                    <el-button @click="handleCurrentChange(page.totalPage)" :disabled="page.pageIndex == page.totalPage"
                        class="btn-prev">尾页</el-button>
                </el-pagination>
            </td>
        </tr>
    </table>

</template>
<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import axios from 'axios'
import { useRoute, useRouter } from 'vue-router';
import { ElMessage, ElMessageBox } from 'element-plus';
const route = useRoute();
const router = useRouter();
const form = reactive({
    roleId: '',
    id: []
})
//编号
const indexMethod = (index: number) => {
    return index + 1;
}
//分页
const page = reactive({
    roleName: '',
    pageIndex: 1,
    pageSize: 3,
    totalCount: 0,
    totalPage: 0
})

const roles = ref('')
const dialogFormVisible = ref(false)
const dialogTableVisible = ref(false);


//打开添加对话框
const openUserRoleAdd = (row: any) => {
    // console.log(row.roleId)
    form.roleId = row.roleId
    roles.value = row.roleName
    dialogFormVisible.value = true
    backfillDepartment(row.roleId);
}

//分页
const handleSizeChange = (val: number) => {
    page.pageSize = val;
    getRoleList();
}
const handleCurrentChange = (val: number) => {
    page.pageIndex = val;
    getRoleList();
}

//部门信息
const defaultProps = {
    label: 'label',
}
const data = [
    {
        label: '选择部门',
        children: [
            {
                value: 1,
                label: 'IT信息部'
            },
            {
                value: 2,
                label: '人力资源部'
            },
            {
                value: 3,
                label: '财务部'
            },
            {
                value: 4,
                label: '销售部'
            },
            {
                value: 5,
                label: '行政部'
            },
        ],
    },
]
const defaultProps1 = {
    id: 'id',
    label: 'userName',
}
//获取用户
const userList = ref([])
const getUserList = (data: any, checked: any) => {
    // console.log(data.value)
    // userList.value.length=0;
    if (checked) {
        // userList.value = [];
        axios.get("/api/UserInfo/GetDepartmentUser?departmentId=" + data.value)
            .then(res => {
                userList.value = userList.value.concat(res.data.data)
                // console.log(userList.value)
            })
            .catch(err => {
                console.log(err);
            })
    }
    else {
        userList.value = userList.value.filter(x => x.departmentId !== data.value)
    }
}
const defaultProps0 = [
    {
        userName: '请选择用户',
        children: userList
    }
]
//获取用户ID
let user = ref([])
const getUserId = (userList: any, check: any) => {
    if (check) {
        user.value.push(userList.id)
    }
    else {
        user.value = user.value.filter((x: any) => x != userList.id)
    }
    // console.log(user.value)
    form.id = user.value
    console.log(form.id)
}

//添加用户角色
const addUserRole = () => {
    // console.log(userId)
    // console.log(form.id)
    axios.post("/api/UserRole/AddUserRole", form)
        .then(res => {
            if (res.data.code == 0) {
                ElMessage.success("添加成功");
                dialogFormVisible.value = false;
                dialogTableVisible.value = true;
                getRoleUser();
            }
        })
        .catch(err => {
            console.log(err);
        })
}

//打开删除用户角色对话框
const openDelUserRole = (row: any) => {
    // console.log(row.roleId);
    form.roleId = row.roleId
    roles.value = row.roleName;
    dialogTableVisible.value = true;
    getRoleUser();
}

//根据角色ID获取用户
const roleUser = ref([])
const getRoleUser = () => {
    axios.get("/api/UserInfo/GetRoleUser?roleId=" + form.roleId)
        .then(res => {
            roleUser.value = res.data.data
            // console.log(roleUser.value[0].roleId)
        })
        .catch(err => {
            console.log(err);
        })
}

//删除用户角色
const delUserRole = (row: any) => {
    console.log(row)
    ElMessageBox.confirm(
        '确认删除吗?',
        '警告',
        {
            confirmButtonText: '确认',
            cancelButtonText: '取消',
            type: 'warning',
        }
    )
        .then(() => {
            console.log(row)
            axios.post("/api/UserRole/DelUserRole", row)
                .then(res => {
                    if (res.data.code == 0) {
                        ElMessage.success("删除成功");
                        getRoleUser();
                    }
                    else {
                        ElMessage.error("删除失败");
                    }
                })
                .catch(err => {
                    console.log(err);
                })
        })
        .catch(() => {
            ElMessage({
                type: 'info',
                message: '已取消该操作',
            })
        })
}

//打开用户角色添加对话框
const openUserRoleAdd1 = (row: any) => {
    dialogFormVisible.value = true
    // console.log(row.roleId)
    dialogTableVisible.value = false
    backfillDepartment(row.roleId)
}

const defaultCheckedDepartmentId = ref([])
const defaultCheckedUserId = ref([])

//返填部门
const backfillDepartment = (roleId: any) => {
    // console.log(form.roleId)
    axios.get("/api/UserInfo/GetUserModelAxync?roleId=" + roleId)
        .then(res => {
            defaultCheckedDepartmentId.value = res.data.data.map(x => x.departmentId)
            // backfillUser(roleId)
            console.log(defaultCheckedDepartmentId.value)
            backfillUser(roleId)
        })
        .catch(err => {
            console.log(err);
        })
}

const backfillUser = (roleId: any) => {
    // console.log(form.roleId)
    axios.get("/api/UserInfo/GetUserModelAxync?roleId=" + roleId)
        .then(res => {
            defaultCheckedUserId.value = res.data.data.map(x => x.id)
            console.log(defaultCheckedUserId.value);
        })
        .catch(err => {
            console.log(err);
        })
}

//获取角色
const roleList = ref([])
const getRoleList = () => {
    axios.get("/api/Role/GetRole", {
        params: {
            RoleName: page.roleName,
            PageIndex: page.pageIndex,
            PageSize: page.pageSize
        }
    })
        .then(res => {
            roleList.value = res.data.data.list
            page.totalCount = res.data.data.totalCount
            page.totalPage = res.data.data.totalPage
        })
        .catch(err => {
            console.log(err);
        })
}

//删除角色
const delRole = (row: any) => {
    ElMessageBox.confirm(
        '确认删除吗?',
        '警告',
        {
            confirmButtonText: '确认',
            cancelButtonText: '取消',
            type: 'warning',
        }
    )
        .then(() => {
            axios.post("/api/Role/DelRole", row)
                .then(res => {
                    if (res.data.code == 0) {
                        ElMessage.success("删除成功");
                        getRoleList();
                    }
                    else {
                        ElMessage.error("删除失败");
                    }
                })
                .catch(err => {
                    console.log(err);
                })
        })
        .catch(() => {
            ElMessage({
                type: 'info',
                message: '已取消该操作',
            })
        })

}

//刷新对话框
const handleClose = (done: () => void) => {
    done();
    location.reload();
}


onMounted(() => {
    getRoleList();
})
</script>